<script setup lang="ts">
import { defineProps, defineEmits, ref } from 'vue';
import type { Card } from '../../types/card';
import { useI18n } from 'vue-i18n';
import { formatAmount } from "../../utils/index";
import Gold_Visa from '../../assets/imgs/images/card/visa_gold.png';
import Default_Visa from '../../assets/imgs/images/card/visa_default.png';
import Gold_Master from '../../assets/imgs/images/card/master_gold.png';
import Default_Master from '../../assets/imgs/images/card/master_default.png';

const props = defineProps<{
  card: Card;
  refreshingBalance: boolean;
  refreshingCardId: number;
  sendingCode: boolean;
  verifyLoading: boolean;
  showOperatorBtn: boolean;
}>();

const { t } = useI18n()
const emit = defineEmits(['handleViewDetails', 'handleRecharge', 'handleTransfer', 'handleRefreshBalance', 'handleSetPin', 'handleViewTransactions', 'handleActivate', 'handleResendCode', 'setEditCard', 'handleViewBalanceLogs', 'handleViewTransferRecordLogs', 'handleCancel']);
const showCardDetails = ref(false);
const showBalance = ref(false);
// 获取卡片背景
const getBackgroundImage = () => {
  if (props.card?.udpayCardScheme === 'VISA') {
      return props.card?.category?.level >= 5 ? Gold_Visa : Default_Visa
  } else {
      return props.card?.category?.level >= 5 ? Gold_Master : Default_Master
  }
};
// 复制卡号
const copyToClipboard = () => {
    const copyText = showCardDetails && props.card.udpayCardNumber ? props.card.udpayCardNumber : props.card.udpayCardBin + '********'
    navigator.clipboard.writeText(copyText.replace(/\s/g, ''));
    setTimeout(() => {
        // toast.success(t('cards.copySuccess'));
    }, 500);
};
const toggleCardDetails = () => {
  showCardDetails.value = !showCardDetails.value;
};
const toggleBalance = () => {
  showBalance.value = !showBalance.value;
};
const handleViewDetails = () => {
  emit('handleViewDetails', props.card);
};
const handleRecharge = () => {
  emit('handleRecharge', props.card);
};
const handleTransfer = () => {
  emit('handleTransfer', props.card);
};
const handleRefreshBalance = () => {
  emit('handleRefreshBalance', props.card);
};
const handleViewTransactions = () => {
  emit('handleViewTransactions', props.card);
};
const handleSetPin = () => {
  emit('handleSetPin', props.card);
};
const handleActivate = () => {
  emit('handleActivate', props.card);
};
const handleResendCode = () => {
  emit('handleResendCode', props.card);
};
const setEditCard = () => {
  emit('setEditCard', props.card);
};
const handleViewBalanceLogs = () => {
  emit('handleViewBalanceLogs', props.card);
};
const handleViewTransferRecordLogs = () => {
  emit('handleViewTransferRecordLogs', props.card);
};
const handleCancel = () => {
  emit('handleCancel', props.card);
};
const getStatusVariant = (status: string) => {
  switch (status.toUpperCase()) {
      case "ACTIVE":
          return "text-white bg-green-500";
      case "PENDING":
          return "text-white bg-yellow-500";
      case "CANCELLED":
          return "text-white bg-red-500";
      case "SUSPENDED":
          return "text-gray-400 bg-secondary";
      default:
          return "text-white bg-gray-500";
  }
};
</script>

<template>
  <div class="flex flex-col items-center justify-center border rounded-xl mb-4 border-gray-400">
    <div class="cardItem w-full max-w-md">
        <!-- {/* 银行卡 */} -->
        <div class="relative rounded-2xl overflow-hidden mb-2">
            <div class="p-2 relative z-10" :style="{
                backgroundImage: `url(${getBackgroundImage()})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
                height: '200px'
                }">
                <!-- {/* 卡号 */} -->
                <div class="absolute bottom-10 left-6 right-[20%]">
                    <div class="flex justify-between items-center">
                        <p class="text-white text-lg font-semibold tracking-wider card-number">
                            {{showCardDetails && card.udpayCardNumber ? card.udpayCardNumber : card.udpayCardBin + '********'}}
                        </p>
                        <div class="flex space-x-2">
                            <span class="iconfont icon-copy" @click="copyToClipboard()"></span>
                            <span class="iconfont icon-eye" v-if="showCardDetails" @click="toggleCardDetails()"></span>
                            <span class="iconfont icon-eye-off-" v-else @click="toggleCardDetails()"></span>
                        </div>
                    </div>
                </div>
                <div class="absolute top-2 left-4 text-white text-sm">
                    <p>{{card?.category?.name}}</p>
                </div>
                <!-- 有效期 -->
                <div class="absolute bottom-0 left-[50%]">
                    <p class="text-white font-medium">
                        {{showCardDetails && card.udpayExpireDate ? card.udpayExpireDate : '**/**'}}
                    </p>
                </div>
                <!-- 状态展示 -->
                <div class="absolute bottom-2 left-4">
                    <span :class="`inline-flex items-center rounded-full border text-xs px-1 py-0.5 border-transparent text-[0.5rem] transition-colors ${getStatusVariant(card.udpayCardStatus)}`">{{card.udpayCardStatus}}</span>
                </div>
            </div>
        </div>
        <!-- {/* 余额 */} -->
        <div class="border rounded-xl px-4">
            <div class="flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <p class="text-white text-sm opacity-80">余额</p>
                    <p class="text-white font-semibold text-lg">
                        {{showBalance
                            ? `${formatAmount(card.udpayAvailableBalance)}`
                            : '***.** USD'}}
                    </p>
                    <span class="iconfont icon-eye" v-if="showCardDetails" @click="toggleBalance()"></span>
                    <span class="iconfont icon-eye-off-" v-else></span>
                </div>
                <div class="flex items-center space-x-3">                    
                    <span
                      v-if="card.udpayCardStatus.toUpperCase() === 'ACTIVE'"
                      @click="handleRecharge()"
                      class="operBtn text-white px-3 py-1 rounded-lg text-sm"
                    >
                        {{t("home.account.topUp")}}
                    </span>
                    <span
                      @click="handleTransfer()"
                        class="operBtn text-white px-3 py-1 text-sm"
                    >
                        {{t("home.account.transfer")}}
                    </span>
                </div>
            </div>
        </div>
        <!-- {/* 操作按钮 */} -->
        <div class="grid grid-cols-4 gap-2 mt-2" v-if="showOperatorBtn">
            <!-- {/* 查看详情 */} -->
            <button v-if="!(sendingCode || verifyLoading || card.udpayCardStatus.toUpperCase() !== 'ACTIVE')" class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all" @click="handleViewDetails">
              <span class="text-sm text-gray-700">{{t("cards.viewDetails")}}</span>
            </button>
            <!-- {/* 刷新余额 */} -->
            <button v-if="card.udpayCardStatus.toUpperCase() === 'ACTIVE'" class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all" :disabled="
              refreshingBalance && refreshingCardId === card.id
              " @click="handleRefreshBalance()"
            >
              <div v-if="refreshingBalance && refreshingCardId === card.id">
                  <Loader2 class="mr-2 h-4 w-4 animate-spin" />{" "}
                  <span class="text-sm text-gray-700">{{t("cards.refreshingBalance")}}</span>
              </div>
              <span v-else class="text-sm text-gray-700">{{t("cards.refreshBalance")}}</span>
            </button>
            <!-- {/* 卡-账单 */} -->
            <button v-if="card.udpayCardStatus.toUpperCase() === 'ACTIVE'" class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all" @click="handleViewTransactions()">
                <span class="text-sm text-gray-700">{{t("cards.transactionsTitle")}}</span>
            </button>
            <!-- {/* 设置PIN码 */} -->
            <button v-if="card.type === 2" class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all" @click="handleSetPin()">
                <span class="text-sm text-gray-700">{{t("cards.setPin")}}</span>
            </button>
            <!-- {/* 激活卡片 */} -->
            <button v-if="card.type === 2" class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all" @click="handleActivate()">
                <span class="text-sm text-gray-700">{{t("cards.activate")}}</span>
            </button>
            <!-- {/* 重新发送激活码 */} -->
            <button v-if="card.udpayCardStatus.toUpperCase() === 'PENDING' && card.type === 2" class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all" @click="handleResendCode()">
                <span class="text-sm text-gray-700">{{t("cards.resendActivationCode")}}</span>
            </button>
            <!-- {/* 更多操作 */} -->
            
                <DropdownMenu v-if="card?.udpayCardStatus.toUpperCase() === 'ACTIVE'">
                    <DropdownMenuTrigger asChild>
                        <button class="py-2 border rounded-lg flex flex-col items-center justify-center transition-all">
                            <span class="text-sm text-gray-700">{{t("common.moreActions")}}</span>
                        </button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent>
                        <!-- {/* 编辑 */} -->
                        <DropdownMenuItem @click="setEditCard()">
                            {{t("cards.edit")}}
                        </DropdownMenuItem>
                        <!-- {/* 余额记录 */} -->
                        <DropdownMenuItem
                            @click="handleViewBalanceLogs()"
                            :disabled="card.udpayCardStatus.toUpperCase() !== 'ACTIVE'"
                        >
                            {{t("balanceLog.title")}}
                        </DropdownMenuItem>
                        <!-- {/* 转账记录 */} -->
                        <DropdownMenuItem
                            @click="handleViewTransferRecordLogs()"
                            :key="card.udpayCardStatus.toUpperCase() !== 'ACTIVE'"
                        >
                            {{t("transferRecordLogs.title")}}
                        </DropdownMenuItem>
                        <!-- {/* 注销 */} -->
                        <DropdownMenuItem
                            class="text-red-600"
                            @click="handleCancel()"
                        >
                            {{t("cards.cancelTitle")}}
                        </DropdownMenuItem>
                    </DropdownMenuContent>
                </DropdownMenu>
        </div>
    </div>
  </div>
</template>

<style scoped>
.cardItem {
  border: 2px solid #303037;
  border-radius: 20px;
}

.chip-icon, .contactless-icon {
  opacity: 0.9;
}
.operBtn {
  background-color: #131311;
  letter-spacing: 6px;
  border-radius: 15px;
  border: 1px solid #2f2f2e;
}
</style>